package vrp;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import vrp.PMF;
import vrp.Delivery;
import vrp.SaleOrder;
import vrp.Customer;
import vrp.Product;

public class DeliveryEditServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {

    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	DateFormat df = new SimpleDateFormat ("yyyy-MM-dd");
        
    	long deliveryID = Integer.parseInt(req.getParameter("delivery"));
    	Key deliveryKey = KeyFactory.createKey(Delivery.class.getSimpleName(), deliveryID);
        Delivery delivery = pm.getObjectById(Delivery.class, deliveryKey);

        String urlSaleOrder = req.getParameter("urlSaleOrder");
        String respondRedirect = "/deliveries.jsp?";
        if (!urlSaleOrder.equals("null")) {
            Key saleOrderKey = delivery.getSaleOrder();
            SaleOrder saleOrder = pm.getObjectById(SaleOrder.class, saleOrderKey);
            respondRedirect += "saleOrder="+saleOrder.getKey().getId()+"&";
        }

        try {
        	long customerID = Integer.parseInt(req.getParameter("customer"));
        	long productID = Integer.parseInt(req.getParameter("product"));
        	int quantity = Integer.parseInt(req.getParameter("quantity"));
            Date date = df.parse(req.getParameter("date"));
            
            if (quantity<=0) {
            	pm.close();
            	resp.sendRedirect(respondRedirect + "error=quantity&");
            	return;
            } else {
	            Key customerKey = KeyFactory.createKey(Customer.class.getSimpleName(), customerID);
	            Key productKey = KeyFactory.createKey(Product.class.getSimpleName(), productID);
	            Product product = pm.getObjectById(Product.class, productKey);
	            int inventory = product.getInventory();
            	
	            if (delivery.getStatus() == 2) { //CANCELLED
	            	delivery.setProduct(productKey);
		            delivery.setQuantity(quantity);
	            } else { //PROCESSING
		            Key oldProductKey = delivery.getProduct();
		            int oldQuantity = delivery.getQuantity();
		            
		            if (oldProductKey.getId() != productID) { //new product
		            	if (inventory < quantity) {
		            		pm.close();
		                	resp.sendRedirect(respondRedirect + "error=inventory&");
		                	return;
		                }
		            	product.setInventory(inventory-quantity);
			            Product oldProduct = pm.getObjectById(Product.class, oldProductKey);
			            oldProduct.setInventory(oldProduct.getInventory() + oldQuantity);
			            pm.makePersistent(product);
			            pm.makePersistent(oldProduct);
		            	delivery.setProduct(productKey);
			            delivery.setQuantity(quantity);
		            } else { //same product
		            	if (inventory < (quantity-oldQuantity)) {
		            		pm.close();
		                	resp.sendRedirect(respondRedirect + "error=inventory&");
		                	return;
		                }
			            product.setInventory(inventory-quantity+oldQuantity);
			            pm.makePersistent(product);
			            delivery.setQuantity(quantity);
		            }
	            }
	            delivery.setCustomer(customerKey);
	            delivery.setDate(date);
	            delivery.setModifiedAt(new Date());
	            pm.makePersistent(delivery);
            }
        } catch (ParseException e) {
			e.printStackTrace();
		} finally {
            pm.close();
        }
        resp.sendRedirect(respondRedirect);
    }
}